﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Library;
using System.Data;

namespace OA.Exam.Front
{
    public partial class ExamPaper : System.Web.UI.Page
    {
        Exam myExam = new Exam();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["UserName"] = "赵亚杰";
                Session["UserId"] = "zyj";
                string userId = Session["UserId"].ToString();
                if (Request["paperId"] != null)
                {
                    string paperId = Request["paperId"].ToString();
                    HiddenPaperId.Value = paperId;
                    
                    //记录开始时间
                    HiddenBeginTime.Value = DateTime.Now.ToString();
                    //试卷名称，分值，时长
                    LabPaperName.Text = myExam.GetRecordOfPaper(paperId).Rows[0]["papername"].ToString();
                    LabScore.Text = myExam.GetRecordOfPaper(paperId).Rows[0]["score"].ToString();
                    LabExamTime.Text = myExam.GetRecordOfPaper(paperId).Rows[0]["examtime"].ToString();
                    //考生，倒计时
                    LabUserName.Text = Session["UserName"].ToString();
                    HiddenExamTime.Value = DateTime.Now.AddMinutes(Convert.ToUInt32(LabExamTime.Text)).ToString();
                    GetTimeLeft();
                    //绑定大题
                    BindBig(paperId);
                    //判断是否已提交过考卷
                    if (myExam.GetStatusOfExamPaper(userId, paperId) == "1")
                    {
                        LabPrompt.Text = "您已提交过试卷，不能重复答题！";
                        BtnSave.Visible = false;
                        BtnLogin.Visible = false;
                        LabTimeLeft.Visible = false;
                    }
                    //若意外退出，未提交状态下，绑定已保存题目答案
                    if (myExam.GetStatusOfExamPaper(userId, paperId) == "0")
                    {
                        string examId = myExam.GetExamId(userId, paperId);
                        myExam.BindHadSaveAnswer(DataListBigQuestion,examId);
                    }
                }
            }
        }

        protected void BindBig(string paperId)
        {
            string sql = "select ItemType,Score,TypeName from Exam_PapersQuestionTypes as a left join Exam_QuestionTypes as b on a.ItemType=b.TypeId where PaperId='" + paperId + "' order by DispOrder";
            DataListBigQuestion.DataSource = DataAccess.getDataTable(sql);
            DataListBigQuestion.DataBind();
        }

        #region 绑定大题
        protected void DataListBigQuestion_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                //大题编号处理
                Label LabNum = (Label)e.Item.FindControl("LabNum");
                switch (LabNum.Text)
                {
                    case "1":
                        LabNum.Text = "一";
                        break;
                    case "2":
                        LabNum.Text = "二";
                        break;
                    case "3":
                        LabNum.Text = "三";
                        break;
                    case "4":
                        LabNum.Text = "四";
                        break;
                    case "5":
                        LabNum.Text = "五";
                        break;
                }

                //题目说明处理
                string itemType = DataListBigQuestion.DataKeys[e.Item.ItemIndex].ToString();
                Label LabDescription = (Label)e.Item.FindControl("LabDescription");
                Label LabScore = (Label)e.Item.FindControl("LabScore");
                switch (itemType)
                {
                    case "00001":
                        LabDescription.Text = "（请在每题后面选择正确还是错误。";
                        break;
                    case "00002":
                        LabDescription.Text = "（下列每题备选答案中，只有一个符合题意的正确答案。请在选项中选择。";
                        break;
                    case "00003":
                        LabDescription.Text = "（下列每题备选答案中，有两个或两个以上符合题意的正确答案。请在选项中选择。";
                        break;
                    case "00004":
                        LabDescription.Text = "（下列每题中（）代表需填空的位置，请在对应的矩形框中填写答案。";
                        LabScore.Text = "）";
                        break;
                    case "00005":
                        LabDescription.Text = "（请在每题对应的矩形框中填写答案。";
                        LabScore.Text = "）";
                        break;
                }
                //绑定小题
                DataList DataListQuestions = e.Item.FindControl("DataListQuestions") as DataList;
                DataListQuestions.DataSource = myExam.GetSmallQuestions(HiddenPaperId.Value, itemType);
                DataListQuestions.DataBind();
            }
        }
        #endregion

        #region 绑定小题
        protected void DataListQuestions_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                //string questionId = DataListBigQuestion.DataKeys[((DataListItem)((e.Item.NamingContainer).NamingContainer)).ItemIndex].ToString();
                HiddenField HfQuestionId = (HiddenField)e.Item.FindControl("HfQuestionId");
                string questionId = HfQuestionId.Value;
                HiddenField HfItemType = (HiddenField)e.Item.FindControl("HfItemType");
                Label LabSubject = (Label)e.Item.FindControl("LabSubject");

                //haha
                //Label LabQNum = (Label)e.Item.FindControl("LabQNum");
                //Label LabNumMark = (Label)((DataListItem)e.Item.NamingContainer.NamingContainer).FindControl("LabNumMark");
                switch (HfItemType.Value)
                {
                    case "00002":
                        DataList DataListRadio = e.Item.FindControl("DataListRadio") as DataList;
                        DataListRadio.DataSource = myExam.GetItemListOfQuestion(questionId);
                        DataListRadio.DataBind();
                        break;
                    case "00003":
                        DataList DataListMultiple = e.Item.FindControl("DataListMultiple") as DataList;
                        DataListMultiple.DataSource = myExam.GetItemListOfQuestion(questionId);
                        DataListMultiple.DataBind();
                        break;
                    case "00004":
                        string[] arr = LabSubject.Text.Trim().Split('（');
                        int textNum = arr.Length - 1;
                        //HtmlGenericControl DivBlank = new HtmlGenericControl("div");
                        //采用声明方式添加文本框，根据需要显示适当的数量
                        for (int i = 1; i <= textNum; i++)
                        {
                            TextBox BlankTextBox = (TextBox)e.Item.FindControl("BlankTextBox" + i.ToString());
                            BlankTextBox.Visible = true;
                        }
                        break;
                }
            }
        }
        #endregion

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            GetTimeLeft();
        }

        void GetTimeLeft()
        {
            DateTime endtime = Convert.ToDateTime(HiddenExamTime.Value);
            TimeSpan ts = endtime.Subtract(DateTime.Now).Duration();

            LabTimeLeft.Text = ts.Hours + "时" + ts.Minutes + "分" + ts.Seconds + "秒";

            if (ts.Minutes == 15 && ts.Seconds == 1)
            {
                LabPrompt.Text = "考试剩余时间已经不到15分钟了，请注意提交试卷！";
            }
            if (ts.Minutes == 0 && ts.Seconds == 1)
            {
                LabPrompt.Text = "时间到，本场考试结束！";
                //系统保存
                BtnSave.Visible = false;
                BtnLogin.Visible = false;
                HiddenStatus.Value = "1";
                SaveExamAnswer();
                //Response.Redirect();
            }
        }
        //提交考卷后跳转
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            HiddenStatus.Value = "1";
            SaveExamAnswer();
            //Response.Redirect();
        }
        //保存考卷
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            HiddenStatus.Value = "0";
            SaveExamAnswer();
        }

        void SaveExamAnswer()
        {
            int i, j, k, l;
            string examId = string.Empty;
            string userId = Session["UserId"].ToString();
            string paperId = HiddenPaperId.Value;

            string answerId = string.Empty;

            //还未提交过试卷
            if (myExam.GetStatusOfExamPaper(Session["UserId"].ToString(), HiddenPaperId.Value) == "-1")
            {
                examId = SqlUtil.GetPrimaryKeyId();

                DateTime beginTime = Convert.ToDateTime(HiddenBeginTime.Value);
                DateTime endTime = beginTime.AddMinutes(Convert.ToUInt32(HiddenExamTime.Value));
                if (!myExam.InsertExamPaper(examId, userId, paperId, 0, "", beginTime, endTime, HiddenStatus.Value))
                {
                    LabPrompt.Text = "提交失败请重试";
                    return;
                }
            }
            else//已提交过
            {
                examId = myExam.GetExamId(userId,paperId);//获取已提交过的考卷编号examId
                if (HiddenStatus.Value == "1")//login or save?
                {
                    myExam.UpdateStatusOfExamPaper(userId, paperId, HiddenStatus.Value);
                }
            }

            for (i = 0; i < DataListBigQuestion.Items.Count; i++)
            {
                string itemType = DataListBigQuestion.DataKeys[i].ToString();
                DataList DataListQuestions = DataListBigQuestion.Items[i].FindControl("DataListQuestions") as DataList;
                for (j = 0; j < DataListQuestions.Items.Count; j++)
                {
                    string answerContent = string.Empty;
                    string questionId = DataListQuestions.DataKeys[j].ToString();
                    answerId = SqlUtil.GetPrimaryKeyId();
                    if (itemType == "00001")
                    {
                        RadioButtonList RabJudge = (RadioButtonList)DataListQuestions.Items[j].FindControl("RabJudge");
                        answerContent = RabJudge.SelectedValue;
                    }
                    if (itemType == "00002")
                    {
                        DataList DataListRadio = DataListQuestions.Items[j].FindControl("DataListRadio") as DataList;
                        for (k = 0; k < DataListRadio.Items.Count; k++)
                        {
                            RadioButton RabItem = (RadioButton)DataListRadio.Items[k].FindControl("RabItem");
                            Label LabRadioItem = (Label)DataListRadio.Items[k].FindControl("LabRadioItem");
                            if (RabItem.Checked)
                            {
                                answerContent = LabRadioItem.Text;
                            }
                        }
                    }
                    if (itemType == "00003")
                    {
                        DataList DataListMultiple = DataListQuestions.Items[j].FindControl("DataListMultiple") as DataList;
                        for (k = 0; k < DataListMultiple.Items.Count; k++)
                        {
                            CheckBox ChbItem = (CheckBox)DataListMultiple.Items[k].FindControl("ChbItem");
                            Label LabMultipleItem = (Label)DataListMultiple.Items[k].FindControl("LabMultipleItem");
                            if (ChbItem.Checked)
                            {
                                answerContent += LabMultipleItem.Text + ",";
                            }
                        }
                        if (answerContent.IndexOf(',') != -1)
                        {
                            answerContent = answerContent.TrimEnd(',');
                        }
                    }
                    if (itemType == "00004")
                    {
                        Label LabSubject = (Label)DataListQuestions.Items[j].FindControl("LabSubject");
                        string[] arr = LabSubject.Text.Trim().Split('（');
                        int textNum = arr.Length - 1;
                        for (l = 1; l <= textNum; l++)
                        {
                            //即使动态生成时拼装id，依然找不到控件，看来是原则性错误，要想找到，需在Page_Load 之前生成？
                            TextBox BlankTextBox = (TextBox)DataListQuestions.Items[j].FindControl("BlankTextBox" + l.ToString());
                            answerContent += BlankTextBox.Text + "|";
                        }
                        if (answerContent.IndexOf('|') != -1)
                        {
                            answerContent = answerContent.TrimEnd('|');
                        }
                    }
                    if (itemType == "00005")
                    {
                        TextBox TxtAnswer = (TextBox)DataListQuestions.Items[j].FindControl("TxtAnswer");
                        answerContent = TxtAnswer.Text;
                    }
                    //保存答案
                    myExam.SaveExamAnswers(answerId, examId, questionId, 0, answerContent);
                }
            }
            LabPrompt.Text = "处理成功";
        }

    }
}

